package com.wman.sheep.mvp.base;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.umeng.analytics.MobclickAgent;
import com.wman.sheep.R;
import com.wman.sheep.common.application.AbsAppContext;
import com.wman.sheep.common.utils.StatusBarCompat;
import com.wman.sheep.common.utils.TDevice;
import com.wman.sheep.common.utils.ToastUtil;
import com.wman.sheep.mvp.presenter.ActivityPresenter;
import com.wman.sheep.mvp.view.IDelegate;
import com.wman.sheep.okhttputils.OkHttpUtils;
import com.wman.sheep.widget.BaseTitleBar;

import java.lang.ref.WeakReference;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Activity基类
 */
public abstract class BaseActivity<T extends IDelegate> extends ActivityPresenter<T>
        implements View.OnClickListener {
    private RelativeLayout mRootView;
    protected LinearLayout mContentView;
    //顶部渐变的背景
    private View mGradient;
    //TitleBar
    protected BaseTitleBar mTitleBar;
    //Loading 进度条ViewStub
    protected ViewStub mLoadingViewStub;
    //Loading View
    protected View mLoadingView;
    public Context context;
    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mRootView = (RelativeLayout) View.inflate(this, R.layout.base_root_view, null);
        mGradient = mRootView.findViewById(R.id.view_gradient);
        mTitleBar = (BaseTitleBar) mRootView.findViewById(R.id.include_action_bar);
        mContentView = (LinearLayout) mRootView.findViewById(R.id.rootView);
        mLoadingViewStub = (ViewStub) mRootView.findViewById(R.id.loading_viewstub);

        super.onCreate(savedInstanceState);
        super.setContentView(mRootView);
        context = mContext;
        unbinder=ButterKnife.bind(this);

//        if(BuildConfig.DEBUG){
//            MobclickAgent.setDebugMode(true);
//        }
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);

        //状态栏的设置，6.0以下的设置为黑色，以上设置为白色
        if (android.os.Build.MANUFACTURER.equals("Xiaomi")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(0XFFFFFFFF);
                StatusBarCompat.MIUISetStatusBarLightMode(getWindow(), true);
            }
        } else if (android.os.Build.MANUFACTURER.equals("Meizu")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().setStatusBarColor(0XFFFFFFFF);
                StatusBarCompat.MIUISetStatusBarLightMode(getWindow(), true);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(0XFFFFFFFF);
        }

        setTitleBar();

        initData();
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                initViewSC();
            }
        });

    }

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * View绘制完成后的初始化
     */
    protected void initViewSC() {
    }

    @Override
    public void onClick(View v) {

    }

    protected void initTitleBar() {
    }

    @Override
    protected void initToolbar() {
        Toolbar toolbar = mViewDelegate.getToolBar();
        if (toolbar != null) {
//            toolbar = (Toolbar) View.inflate(this, R.layout.base_toolbar, null);
//            rootView.addView(toolbar, 0);
//        } else {
            setSupportActionBar(toolbar);
        }
    }

    /**
     * 显示LoadingView
     */
    public void showLoadingView() {
        mLoadingViewStub.setVisibility(View.VISIBLE);
        mLoadingView = mRootView.findViewById(R.id.loading_view);
        mLoadingView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }
    /**
     * 隐藏LoadingView
     */
    public void hideLoadingView() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
    }

    public BaseTitleBar getBaseTitleBar() {
        if (mTitleBar == null) {
            mTitleBar = (BaseTitleBar) mRootView.findViewById(R.id.include_action_bar);
        }
        return mTitleBar;
    }

    private void setTitleBar() {
        if (isShowTitleBar()) {
            mTitleBar.setVisibility(View.VISIBLE);
            mGradient.setVisibility(View.VISIBLE);
        } else {
            mTitleBar.setVisibility(View.GONE);
            mGradient.setVisibility(View.GONE);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mContentView.getLayoutParams();
            lp.setMargins(0, 0, 0, 0);
            mContentView.setLayoutParams(lp);
        }
        initTitleBar();
    }

    /**
     * 是否显示TitleBar
     *
     * @return
     */
    protected boolean isShowTitleBar() {
        return true;
    }

    @Override
    public void setContentView(int layoutId) {
        setContentView(View.inflate(this, layoutId, null));
    }

    @Override
    public void setContentView(View view) {
        mContentView.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 实例化一个UiHandler处理
     */
    private Handler mUiHandler;

    /**
     * 自定义UiHandler,用于处理其他线程发送的消息
     */
    private static class UiHandler extends Handler {
        // 定义BaseFragment的弱引用，以保证虚拟机随时可以回收此页面
        private final WeakReference<BaseActivity> mActivityReference;

        /**
         * 构建自定义的UIHandler，传递当前页面引用(Activity或者BaseFragment)
         *
         * @param activity
         */
        public UiHandler(BaseActivity activity) {
            mActivityReference = new WeakReference<BaseActivity>(activity);
        }

        /**
         * 获取当前页面(Activity或者BaseFragment)
         *
         * @return
         */
        public WeakReference<BaseActivity> getFragmentReference() {
            return mActivityReference;
        }
    }

    /**
     * 处理更新UI任务(派生类需要重写此方法，用于处理自身业务)
     *
     * @param msg
     */
    protected void handleUiMessage(Message msg) {
    }

    /**
     * 发送UI更新操作
     *
     * @param msg
     */
    protected void sendUiMessage(Message msg) {
        getUiHandler().sendMessage(msg);
    }


    /**
     * 发送UI更新操作
     *
     * @param what
     */
    protected void sendEmptyUiMessage(int what) {
        getUiHandler().sendEmptyMessage(what);
    }

    public Handler getUiHandler() {
        if (mUiHandler == null) {
            mUiHandler = new UiHandler(BaseActivity.this) {
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (getFragmentReference() != null && getFragmentReference().get() != null) {
                        try {
                            getFragmentReference().get().handleUiMessage(msg);
                        } catch (IllegalStateException e) {
                        }
                    }
                }
            };
        }
        return mUiHandler;
    }

    @Override
    public void finish() {
        super.finish();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getUiHandler().removeCallbacksAndMessages(null);
        if (mUiHandler != null) {
            mUiHandler = null;
        }
        OkHttpUtils.getInstance().cancelTag(AbsAppContext.context());
        unbinder.unbind();
    }

    /**
     * 显示软键盘
     */
    public void showSoftInput() {
        InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        manager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftInput(Context context) {
        InputMethodManager manager = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null) {
            manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * @param it
     * @return void
     * @Title: startAnimationActivity
     * @Description: 开始动画跳转
     */
    public void startAnimationActivity(Intent it) {
        if (0 == TDevice.getNetworkType()) {
            ToastUtil.showTextToast(AbsAppContext.resources().getString(R.string.common_check_network));
            return;
        }
        startActivity(it);
        overridePendingTransition(R.anim.in_from_right, R.anim.out_of_left);
    }

    /**
     * @param it
     * @param requestCode
     * @return void
     * @Title: startAnimationActivityForResult
     * @Description: 开始动画跳转
     */
    public void startAnimationActivityForResult(Intent it, int requestCode) {
        startActivityForResult(it, requestCode);
        overridePendingTransition(R.anim.in_from_right, R.anim.out_of_left);
    }

    /**
     * @return void
     * @Title: finishAnimationActivity
     * @Description: 动画方式结束页面
     */
    public void finishAnimationActivity() {
        finish();
        overridePendingTransition(R.anim.in_from_left, R.anim.out_of_right);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishAnimationActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
